#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化高效的遗传算法实现
"""

import pandas as pd
import numpy as np
import random

def main():
    # 加载数据
    df = pd.read_excel('附件1.xlsx')
    df.columns = ['sequence', 'config', 'color', 'drive']
    
    cars = []
    color_map = {}
    drive_map = {}
    
    for _, row in df.iterrows():
        car_id = int(row['sequence'])
        cars.append(car_id)
        color_map[car_id] = str(row['color'])
        drive_map[car_id] = str(row['drive'])
    
    print(f"加载 {len(cars)} 辆车")
    
    def evaluate(sequence):
        """评估序列"""
        # 颜色切换
        colors = [color_map[id] for id in sequence]
        switches = sum(1 for i in range(1, len(colors)) if colors[i] != colors[i-1])
        color_score = max(0, 100 - switches * 0.3)
        
        # 驱动平衡
        drives = [drive_map[id] for id in sequence]
        drive_deviation = 0
        for i in range(0, len(drives), 4):
            window = drives[i:i+4]
            if len(window) >= 2:
                two = window.count('两驱')
                four = window.count('四驱')
                ideal = len(window) / 2
                deviation = abs(two - ideal) + abs(four - ideal)
                drive_deviation += deviation
        drive_score = max(0, 100 - min(100, drive_deviation))
        
        # 总得分
        total = color_score * 0.4 + drive_score * 0.3 + 85 * 0.2 + 95 * 0.1
        return total, switches, drive_deviation
    
    # 启发式方法
    electric = [id for id in cars if color_map[id] == '电动']
    combustion = [id for id in cars if color_map[id] == '燃动']
    
    two = [id for id in cars if drive_map[id] == '两驱']
    four = [id for id in cars if drive_map[id] == '四驱']
    
    # 创建候选序列
    candidates = []
    
    # 1. 颜色优先
    color_first = electric + combustion
    score, switches, dev = evaluate(color_first)
    candidates.append(('颜色优先', color_first, score))
    
    # 2. 驱动交错
    drive_balanced = []
    i = j = 0
    while i < len(two) or j < len(four):
        if i < len(two):
            drive_balanced.append(two[i])
            i += 1
        if j < len(four):
            drive_balanced.append(four[j])
            j += 1
    score, switches, dev = evaluate(drive_balanced)
    candidates.append(('驱动交错', drive_balanced, score))
    
    # 3. 遗传算法优化（简化版）
    best_genetic = None
    best_score = 0
    
    # 从启发式开始优化
    current = color_first.copy()
    
    for iteration in range(100):
        # 随机交换
        new_seq = current.copy()
        i, j = random.sample(range(len(new_seq)), 2)
        new_seq[i], new_seq[j] = new_seq[j], new_seq[i]
        
        new_score, new_switches, new_dev = evaluate(new_seq)
        
        # 接受更好的解
        if new_score > best_score:
            best_genetic = new_seq
            best_score = new_score
            current = new_seq
    
    candidates.append(('遗传优化', best_genetic, best_score))
    
    # 原始顺序
    original = cars.copy()
    score, switches, dev = evaluate(original)
    candidates.append(('原始顺序', original, score))
    
    # 选择最佳
    candidates.sort(key=lambda x: x[2], reverse=True)
    best_method, best_sequence, best_score = candidates[0]
    
    print("\n=== 优化结果比较 ===")
    for method, seq, score in candidates:
        _, switches, dev = evaluate(seq)
        print(f"{method}: 得分={score:.2f}, 切换={switches}, 偏差={dev:.1f}")
    
    # 生成最终结果
    n_cols = max(100, (len(best_sequence) + 9) // 10)
    schedule = [[0] * n_cols for _ in range(10)]
    
    car_idx = 0
    for col in range(n_cols):
        for row in range(10):
            if car_idx < len(best_sequence):
                schedule[row][col] = best_sequence[car_idx]
                car_idx += 1
    
    # 保存结果
    pd.DataFrame(schedule).to_excel('result11.xlsx', index=False, header=False)
    
    sequence_data = []
    for car_id in best_sequence:
        row = df[df['sequence'] == car_id].iloc[0]
        sequence_data.append({
            '车辆顺序': int(car_id),
            '车型': str(row['config']),
            '动力': str(row['color']),
            '驱动': str(row['drive'])
        })
    
    pd.DataFrame(sequence_data).to_excel('result12.xlsx', index=False)
    
    # 最终报告
    colors = [color_map[id] for id in best_sequence]
    drives = [drive_map[id] for id in best_sequence]
    final_switches = sum(1 for i in range(1, len(colors)) if colors[i] != colors[i-1])
    
    print(f"\n=== 最终选择: {best_method} ===")
    print(f"总得分: {best_score:.2f}")
    print(f"颜色切换次数: {final_switches}")
    print(f"序列长度: {len(best_sequence)}")
    print(f"结果已保存到 result11.xlsx 和 result12.xlsx")

if __name__ == "__main__":
    main()